<?php

declare(strict_types=1);

namespace App\Services;

use Hyperf\Di\Annotation\Inject;
use App\Exception\ApiException;
use App\Constants\ErrorCode;
use App\Model\PointsRanking;
use App\Model\User;

class PointsRankingService extends BaseService
{

    public function ranking(array $params)
    {
        $user = auth_user();
        $level = ['S', 'A', 'B'];

        $lastMonthYear = get_last_month_year();
        $year = $lastMonthYear['year'];
        $list = [];

        foreach ($level as $key => $val) {
            $pointsRanking = PointsRanking::query()
                ->with(['user' => function ($query) {
                    // 只选择 user 表中的 nickname 和 avatar 字段
                    $query->select('id', 'nickname', 'avatar');
                }])
                ->where('year', $year)
                ->where('month', $params['month'])
                ->where('level', $val)
                ->where('deleted', 0)
                ->orderBy('points', 'DESC')
                ->limit(10)
                ->get(['user_id', 'points']) // 选择 points_ranking 表中的 user_id 和 points 字段
                ->toArray();

            foreach ($pointsRanking as $kkk => $vvv) {
                $rank = $kkk + 1;
                $pointsRanking[$kkk]['rank'] = $rank;
                $pointsRanking[$kkk]['rank_icon'] = env('HTTP_HOST') . '/public/images/rank/' . $rank . '.png';

                // 删除 user_id 字段
                unset($pointsRanking[$kkk]['user_id']);
                
                // 删除关联的 user 中的 id 字段
                unset($pointsRanking[$kkk]['user']['id']);
            }

            $list[$val] = $pointsRanking;
        }

        // 获取当前用户的排名信息
        $userRanking = PointsRanking::query()
            ->select('rank', 'points')
            ->where('user_id', $user['id'])
            ->where('year', $year)
            ->where('month', $params['month'])
            ->where('level', $user['level'])
            ->where('deleted', 0)
            ->first();

        $self = $userRanking ?? (object)[];

        return ['self' => $self, 'list' => $list];
    }



    //排行榜各等级分页（废弃）
    public function getRankingData(array $params)
    {
        $lastMonthYear = get_last_month_year();
        $year = $lastMonthYear['year'];

        $list = [];
        $model = PointsRanking::query()->with('user')->where('level', $params['level'])->where('year', $year)->where('month', $params['month']);
        $list = $this->usePage($model, 'points')->toArray();
        foreach($list['data'] as $key=>$val)
        {
            $rank = $key+1;
            $list[$key]['rank'] = $rank;
            $list[$key]['rank_icon'] = env('HTTP_HOST').'/public/images/rank/'.$rank.'.png';
        }

        return $list;
    }

}